<template>
  <view>
    <yy-paging
      v-model="dataList"
      @onRefresh="onRefresh"
      @query="queryList"
      ref="paging"
      :auto="true"
      bgColor="#fff"
      @scroll="scroll"
      :refresher-enabled="true"
    >
      <!--  -->
      <template #top>
        <u-navbar
          back-text=""
          :is-back="false"
          :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
          :border-bottom="false"
          :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
        >
          <view class="grid grid-cols-3 items-center px-3 w-full">
            <view class="flex col-span-1 items-center" @click="pageReturn">
              <image src="/static/dddr128.png" mode="aspectFill" class="size-6" />
            </view>
            <view class="flex col-span-1 justify-center">
              <view class="text-[#000] font-bold text-base"> 充值 </view>
            </view>
            <view class="flex col-span-1 justify-end" @click="vk.navigateTo('/pages/my/rechargeDetails')">
              <view class="text-[.875rem] text-[#5C6068]"> 消费记录 </view>
            </view>
          </view>
        </u-navbar>
      </template>

      <template #empty>
        <yy-empty></yy-empty>
      </template>
      <template #loadingMoreNoMore>
        <yy-nomore text=""></yy-nomore>
      </template>
      <view class="flex flex-col gap-3 justify-center items-center p-4">
        <view class="text-[.75rem] text-[#5C606]"> 我的钓钻 </view>
        <view class="text-[2rem] text-[#161A24] font-bold"> {{ d.diamond }} </view>
        <view class="text-[.875rem] text-[#161A24] font-medium w-full text-left"> 充值 </view>
        <view class="grid grid-cols-3 gap-3 w-full">
          <view
            class="rounded-[.5rem] flex flex-col gap-2 py-[.875rem] border-[.0625rem]"
            @click="select(k)"
            v-for="(i, k) in d.list"
            :key="k"
            :class="key == k ? 'border-[#00A9AB] bg-[#E6F7F7]' : ' border-transparent bg-[#F4F6F8]'"
          >
            <view class="flex gap-1 justify-center items-center">
              <view class="text-[1.125rem] text-[#161A24] font-bold"> {{ i.coin_base }} </view>
              <view class="text-[.75rem] text-[#161A24] font-medium"> 钻 </view>
            </view>
            <view class="text-[.75rem] text-[#8E9299] text-center"> {{ i.price }}元 </view>
          </view>
        </view>
        <!-- <button></button> -->

        <button
          :disabled="disabledApple || initializeLoading"
          :loading="loadingApple"
          hover-class="none"
          :class="disabledApple || initializeLoading ? '!bg-[#00A9AB]/60' : '!bg-[#00A9AB]'"
          class="rounded-full h-[2.75rem] w-[88%] flex justify-center items-center mt-3 after:border-none"
          @click="rechargeNow"
          v-if="d.list && d.list.length > 0"
        >
          <view class="text-[1rem] text-[#FFFFFF] font-medium">立即充值{{ d.list[key]?.price }}元</view>
        </button>
        <view class="flex items-center">
          <!-- <view
            class="size-[.75rem] rounded-sm flex items-center justify-center"
            :style="{ backgroundColor: isAgree ? '#00A9AB' : 'transparent' }"
            :class="isAgree ? '' : 'border border-[#919499]'"
            @click="isAgree = !isAgree"
          >
            <text v-if="isAgree" class="text-white text-[.625rem]">✓</text>
          </view> -->
          <view class="flex items-center px-2 leading-none" @click="isAgree = !isAgree">
            <image src="/static/dddr120.png" mode="aspectFill" class="size-3" v-if="!isAgree" />
            <image src="/static/dddr121.png" mode="aspectFill" class="size-3" v-if="isAgree" />
          </view>
          <view class="text-[.6875rem] text-[#8E9299]">
            <text>我已阅读并同意</text>
            <text class="text-[#00A9AB]" @click.stop="vk.navigateTo('/pages/login/agreement?type=3')">
              《钓钻购买协议》
            </text>
            <!-- <text>及</text>
            <text class="text-[#00A9AB]" @click.stop="vk.navigateTo('/pages/login/agreement?type=4')">
              《安全提示》
            </text> -->
          </view>
        </view>
        <!-- 充值说明： -->
        <!-- <view class="flex flex-col text-[.75rem] text-[#8E9299] w-full text-left mt-3">
          <view class="text-[.875rem] text-[#5C6068] font-medium"> 充值说明： </view>
          <u-parse :html="content" class="text-[.75rem] text-[#8E9299]"></u-parse>
        </view> -->
      </view>
    </yy-paging>
    <yy-recharge
      :modelValue="modelValue"
      title="选择支付方式"
      :price="d.list[key]?.price"
      @confirm-purchase="confirmPurchase"
      @update:modelValue="modelValue = $event"
      :disabledAndroid="disabledAndroid"
      :loadingAndroid="loadingAndroid"
    ></yy-recharge>
  </view>
</template>

<script>
  import { Iap, IapTransactionState } from '/common/js/iap.js'
  export default {
    data() {
      return {
        isScroll: false, // 是否滚动
        dataList: [], // 数据列表
        key: 0, // 当前选中的充值选项索引
        isAgree: true, // 是否同意协议
        modelValue: false, // 支付弹窗显示状态
        d: {
          diamond: 0, // 钻石数量
          list: [] // 充值选项列表
        },
        //
        content: '', // 内容
        order_no: '', // 订单号
        platform: '', // 平台类型
        //dddd
        title: 'iap', // IAP标题
        loadingApple: false, // 加载状态
        disabledApple: false, // 是否禁用
        productId: '', // 产品ID
        productList: [], // 产品列表
        disabledAndroid: false, // 是否禁用Android平台
        loadingAndroid: false, // 是否禁用Android平台
        initializeLoading: false
      }
    },
    onLoad(options) {},
    onShow() {
      this.platform = uni.getSystemInfoSync().platform // android   //ios
    },

    methods: {
      pageReturn() {
        vk.navigateBack()
      },
      async confirmPurchase(e) {
        vk.showLoading('支付中...')
        let t = this
        t.loadingAndroid = true
        t.disabledAndroid = true
        const payType = e.name === '微信' ? 'wechat' : 'alipay'
        const res = await api.getPayParams({
          order_no: this.order_no,
          pay_type: payType
        })
        console.log('payType==> ', payType)
        if (payType === 'wechat') {
          uni.requestPayment({
            provider: 'wxpay',
            orderInfo: res.data.params,
            success(res) {
              vk.toast('支付成功', 300, e => {
                t.modelValue = false
                t.$refs.paging.reload()
              })
            },
            fail(e) {
              vk.toast('支付失败')
            },
            complete() {
              vk.hideLoading()
              t.loadingAndroid = false
              t.disabledAndroid = false
            }
          })
        }
        if (payType === 'alipay') {
          uni.requestPayment({
            provider: 'alipay',
            orderInfo: res.data.params,
            success: ress => {
              vk.toast('支付成功', 300, e => {
                t.modelValue = false
                t.$refs.paging.reload()
              })
            },
            fail: err => {
              vk.toast('支付失败')
            },
            complete() {
              vk.hideLoading()
              t.loadingAndroid = false
              t.disabledAndroid = false
            }
          })
        }
      },
      rechargeNow() {
        vk.pubfn.debounce(async () => {
          if (!this.isAgree) return vk.toast('请先阅读并同意相关协议', 'none')
          let res = await api.createOrder({
            id: this.d.list[this.key].id
          })
          this.order_no = res.data.order_no
          if (this.platform == 'ios') {
            this.loadingApple = true
            this.disabledApple = true
            this.iosPayment()
          } else {
            this.androidPayment()
          }
        }, 500)
      },
      // 验证订单
      async restore() {
        try {
          const transactions = await this._iap.restoreCompletedTransactions({
            username: ''
          })
          console.log('transactions==> ', transactions)

          if (!transactions.length) return
          for (const element of transactions) {
            console.log('element==> ', element)
            switch (element.transactionState) {
              case IapTransactionState.purchased:
                console.log('11==> ', 11)
                let res = await api.applePay({
                  receipt_data: element.transactionReceipt,
                  order_no: element.payment.username,
                  trid: element.transactionIdentifier,
                  state: element.transactionState
                })
                console.log('res==> ', res)
                if (!res.code) return vk.toast(res.msg)
                await this._iap.finishTransaction(element)
                break
              case IapTransactionState.failed:
                console.log('22==> ', 22)
                // 关闭未支付的订单
                await this._iap.finishTransaction(element)

                break
              default:
                break
            }
          }
        } catch (e) {
          console.log('e==> ', e)
          uni.hideLoading()
        }
      },
      // 苹果支付
      async iosPayment() {
        this.loadingApple = true
        vk.showLoading('支付处理中...')

        this._iap
          .requestPayment({
            productid: this.productId,
            manualFinishTransaction: true,
            username: this.order_no
          })
          .then(async result => {
            console.log('result==> ', result)

            //  在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
            let res = await api.applePay({
              receipt_data: result.transactionReceipt,
              order_no: result.payment.username,
              trid: result.transactionIdentifier,
              state: result.transactionState
            })
            console.log('res==> ', res)
            //验证成功后关闭订单
            await this._iap.finishTransaction(result)
            this.$refs.paging.reload()
          })
          .catch(err => {
            vk.hideLoading()
            console.log('🚀 ~ iosPayment ~ err:', err)
          })
          .finally(() => {
            vk.hideLoading()

            this.loadingApple = false
            this.disabledApple = false

            // this.disabledApple = false
          })
      },
      async init() {
        this.initializeLoading = true
        // vk.showLoading('检测支付环境...')
        try {
          // 初始化，获取iap支付通道
          await this._iap.init()

          // 从苹果服务器获取产品列表
          this.productList = await this._iap.getProduct()
          this.productId = this.d.list.map(item => item.productid)[this.key]
        } catch (e) {
          uni.hideLoading()
        } finally {
          this.initializeLoading = false
        }
        if (this._iap._ready) {
          this.restore()
        }
      },
      async androidPayment() {
        this.modelValue = true
      },
      select(k) {
        this.key = k
        this.productId = this.d.list[k].productid
        console.log('this.productId==> ', this.productId)
      },
      onRefresh() {},
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
      },

      async queryList(page, limit) {
        let res = await api.getDiamondList()
        this.d = res.data
        this.content = res.data.recharge_tips.replace(/\n/g, '<br/>')

        if (this.platform == 'ios') {
          this._iap = new Iap({
            products: res.data.list.map(item => item.productid) // 苹果开发者中心创建
          })
          this.init()
        }
        this.$refs.paging.complete([''])
      }
    }
  }
</script>

<style lang="scss" scoped></style>
